Codeforces 825 F Minimal Labels(反向拓扑排序)

109 篇文章 0 订阅
104 篇文章 0 订阅

题目地址:http://codeforces.com/contest/825/problem/E
题意:给出一个有n个顶点和m个边的有向非循环图。任何一对顶点之间不存在自环或多边,要为所有顶点分配标签,要求如下:

  • 标签形成长度为n的整数序列的有效排列,使得从1到n的每个整数在其中出现一次。
  • 如果存在从顶点v到顶点u的边缘,那么标签v应该小于标签u。
  • 输出的排列应该是字典序最小的。

思路:一看到题目就想到是拓扑排序的题目,因为后面排到的序号小的优先级比前面排到的序号大的优先级高,所以可以反向拓扑排序。

#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define LL long long 
#define N 100010
#define M 50010
#define inf 0x3f3f3f3f3f3f3f3f
using namespace std;
const LL mod = 1e9 + 7;
const double eps = 1e-9;
vector<int> mapp[N];
int n, m, ans;
int in[N], num[N];
void init() {
    for (int i = 0; i <= n; i++) {
        mapp[i].clear();
    }
    memset(in, 0, sizeof(in));
    ans = n;
}
void topu() {
    int vis[N];
    memset(vis, false, sizeof(vis));
    priority_queue<int> q;
    for (int i = 1; i <= n; i++) {
        if (in[i] == 0) {
            q.push(i);
            vis[i] = true;
        }
    }
    while (!q.empty()) {
        int x = q.top();
        q.pop();
        num[x] = ans--;
        for (int i = 0; i < mapp[x].size(); i++) {
            int y = mapp[x][i];
            if (vis[y]) {
                continue;
            }
            in[y]--;
            if (in[y] == 0) {
                q.push(y);
                vis[y] = true;
            }
        }
    }
}
int main() {
    cin.sync_with_stdio(false);
    int a, b;
    while (cin >> n >> m) {
        init();
        for (int i = 0; i < m; i++) {
            cin >> a >> b;
            mapp[b].push_back(a);
            in[a]++;
        }
        topu();
        for (int i = 1; i <= n; i++) {
            cout << num[i] << " ";
        }
        cout << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值